package com.hnjd.headline.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hnjd.headline.pojo.Type;
import com.hnjd.headline.pojo.dto.HeadlineDetail;
import com.hnjd.headline.pojo.dto.HeadlineDto;
import com.hnjd.headline.pojo.dto.PageInfo;
import com.hnjd.headline.pojo.dto.PortalVo;
import com.hnjd.headline.service.HeadlineService;
import com.hnjd.headline.service.TypeService;
import com.hnjd.headline.utils.Result;
import com.hnjd.headline.utils.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/portal")
@CrossOrigin
public class PortalController {

    @Autowired
    private TypeService typeService;

    @Autowired
    private HeadlineService headlineService;

    /**
     * 查询所有类型
     *
     * @return
     */
    @GetMapping("/findAllTypes")
    public Result findAllTypes() {
        List<Type> typeList = typeService.list();
        return Result.ok(typeList);
    }

    /**
     * 首页分页查询
     *
     * @param portalVo 条件查询
     * @return
     */
    @PostMapping("/findNewsPage")
    public Result findNewsPage(@RequestBody PortalVo portalVo) {
        IPage<HeadlineDto> page = headlineService.findNewsPage(portalVo);

        // 对齐查询结果
        PageInfo<HeadlineDto> pageInfo = new PageInfo<>();
        pageInfo.setPageData(page.getRecords());
        pageInfo.setPageNum(page.getCurrent());
        pageInfo.setPageSize(page.getSize());
        pageInfo.setTotalPage(page.getPages());
        pageInfo.setTotalSize(page.getTotal());

        Map<String, Object> data = Map.of("pageInfo", pageInfo);
        return Result.ok(data);
    }

    /**
     * 显示新闻详情
     *
     * @param hid 新闻id
     */
    @PostMapping("/showHeadlineDetail")
    public Result showHeadlineDetail(@RequestParam("hid") Integer hid) {
        if (hid == null) {
            return Result.build(ResultCodeEnum.BAD_REQUEST);
        }

        HeadlineDetail headlineDetail = headlineService.getHeadlineById(hid);

        // 数据对齐
        Map<String, Object> data = Map.of("headline", headlineDetail);
        return Result.ok(data);
    }
    
}
